import cv2
import numpy as np

# 读取图像
image = cv2.imread('imgs/triangle.png')

# 转换为灰度图像
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)

# 应用Canny边缘检测
edges = cv2.Canny(gray, 50, 150, apertureSize=3)

# 使用霍夫变换检测直线
lines = cv2.HoughLines(edges, 1, np.pi / 180, 200)

# 对于每一条检测到的直线
for line in lines:
    for rho, theta in line:
        # 将极坐标(rho, theta)转换为笛卡尔坐标(a, b)
        a = np.cos(theta)
        b = np.sin(theta)
        x0 = a * rho
        y0 = b * rho
        print(f"rho: {rho} ,theta:{theta}")
        # 计算直线与图像边界的交点
        x1 = int(x0 + 1000 * (-b))
        y1 = int(y0 + 1000 * (a))
        x2 = int(x0 - 1000 * (-b))
        y2 = int(y0 - 1000 * (a))

        # 在图像上绘制直线
        cv2.line(image, (x1, y1), (x2, y2), (0, 0, 255), 2)

# 显示结果
cv2.imshow('Detected Lines', image)
cv2.waitKey(0)
cv2.destroyAllWindows()